#!/bin/bash

game_saved_dir=/home/steam/Steam/steamapps/common/PalServer/Pal/Saved
game_saved_backup_dir=/home/steam/palbackup

while [ $# -gt 0 ]; do
    case $1 in
      --game-saved-dir)
        game_saved_dir=$2
        shift
        shift
        ;;
      --game-saved-backup-dir)
        game_saved_backup_dir=$2
        shift
        shift
        ;;
    *)
        echo "Unknown argument: $1"
        exit 1
        ;;
    esac
done

if [ ! -d $game_saved_dir ]; then
    echo "$game_saved_dir not exist"
    exit 1
fi

if [ ! -d $game_saved_backup_dir ]; then
    echo "$game_saved_backup_dir not exist"
    exit 1
fi

backup_list=$(ls $game_saved_backup_dir)
if [ -z "$backup_list" ]; then
    echo "no backup exist"
    exit 1
fi

for f in $backup_list; do
    echo $f
done

echo "Please enter which backup you want to restore: "
read backup_filename

backup_file_path=${game_saved_backup_dir}/${backup_filename}
if [ ! -f $backup_file_path ]; then
    echo "$backup_file_path not exist"
    exit 1
fi

echo "Are you sure you want to restore game saved from $backup_file_path ?(Y/N)"
read confirm
if [ ! $confirm = "Y" ]; then
    echo "End by user"
    exit
fi

systemd_unit=pal-server

echo "Stop PalServer"
sudo systemctl stop $systemd_unit

cd $game_saved_dir/../
cur_dir=$(pwd)
if [ -d Saved.bak ]; then
    rm -rf Saved.bak
fi
mv Saved Saved.bak
echo "Backup current game saved to ${cur_dir}/Saved.bak"

tar zxvf $backup_file_path

echo "Starting palServer..."
systemctl start pal-server
systemctl -l --no-pager status $systemd_unit

if systemctl --quiet is-active "$systemd_unit"
then
    echo "PalServer is running successfully, enjoy!"
fi


